
// INCLUDES ********************************************************************

#include "FontCache.h"

#include "FileUtils.h"

#include "Logger.h"

#include <thread>



// NAMESPACES ******************************************************************

namespace
{
    void AddFontAsync( const std::string& fontName)
    {
        Meteor::FontCache::Instance().AddObject( fontName);
        
        Meteor::FontCache::Instance().ObjectAdded( fontName);
    }
}

// *****************************************************************************

#pragma mark -
#pragma mark Constructor/Destructor
// -----------------------------------------------------------------------------

Meteor::FontCache::FontCache()

: Cache()

{

}

// -----------------------------------------------------------------------------

Meteor::FontCache::~FontCache()
{
    Flush();
}

#pragma mark -
#pragma mark Add/remove fonts
// -----------------------------------------------------------------------------

FTFont* Meteor::FontCache::AddObject( std::string fileName)
{
    std::string filePath = Meteor::FileUtils::ResourcePathForFile( fileName);

    FTFont* newFont = new FTTextureFont( filePath.c_str());
    
    if ( newFont == 0)
    {
         Logger::DebugLog( "FontCache::AddObject - Error creating font.");
        
        return 0;
    }
    
    if ( newFont->Error())
    {
        delete newFont;
        
        Logger::DebugLog( "FontCache::AddObject - Error creating font.");
        
        return 0;
    }
    
    newFont->CharMap( ft_encoding_unicode);
    
    std::pair<FTFont*, int> newCacheObject( newFont, 1);
    
    mObjects.insert( std::pair<std::string, std::pair<FTFont*, int> >( fileName, newCacheObject));
    
    return newFont;
}

// -----------------------------------------------------------------------------

void Meteor::FontCache::AddObjectAsync( const std::string& fileName, Meteor::Function* fileAdded)
{
    if ( mAsyncFiles.find( fileName) != mAsyncFiles.end() ||
         mObjects.find( fileName) != mObjects.end())
    {
        Logger::DebugLog( "FontCache::AddObjectAsync - file already added");
    
        return;
    }

    mAsyncFiles.insert( std::pair<std::string, Meteor::Function*>( fileName, fileAdded ));
    
    std::string filenameToUse = ( *mAsyncFiles.find( fileName)).first;

    std::thread addingThread( AddFontAsync, filenameToUse);

    addingThread.detach();
}

